// pages/video/video.js
import request from '../../utils/request'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    navList:[],
    navId:'',
    videoList:[],
    videoId:'',
    videoUpdateTime:[],
    isTriggered:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad:function(options) {
    this.getNavListData()
  },
  // 获取导航栏菜单
  async getNavListData(){
    const result = await request('/video/group/list')
    const navList = result.data.slice(0,14)
    const navId = navList[0].id
    this.setData({
      navList,
      navId
    })
    this.getVideoListData(this.data.navId)
  },
  //改变选中
  changeNavId(event){
    const navId = event.currentTarget.id
    this.setData({
      navId:navId >>> 0,
      videoList:[]
    })
    this.getVideoListData(this.data.navId)
  },
    async getVideoListData(id){
      wx.showLoading({
        title: '加载中...'
      })
      const videoListData = await request('/video/group',{id})
      wx.hideLoading()
      this.setData({
        isTriggered:false
      })
      let index = 0
      const videoList = videoListData.datas.map(item=>{
        item.id = index++
        return item
      })
      this.setData({
        videoList
      })
  },
  //控制视频播放
  handlerPlay(event){
    let vid = event.currentTarget.id
    this.setData({
      videoId:vid
    })
    this.videoContext = wx.createVideoContext(vid)
    let {videoUpdateTime} = this.data
    const videoItem = videoUpdateTime.find(item=>item.vid === vid)
    if(videoItem){
      this.videoContext.seek(videoItem.currentTime)
    }
    this.videoContext.play()
  },
  //进度条控制
  handlerUpdateTime(event){
    const {videoUpdateTime} = this.data
    const updateTime = {
      vid: event.currentTarget.id,
      currentTime:event.detail.currentTime
    }
    let updateTimeItem = videoUpdateTime.find(item=>item.vid===updateTime.vid)
    if(updateTimeItem){
      updateTimeItem.currentTime=event.detail.currentTime
    }else{
      videoUpdateTime.push(updateTime)
    }
    this.setData({
      videoUpdateTime
    })
  },
  //视频结束
  handlerEnd(event){
    let vid = event.currentTarget.id
    const {videoUpdateTime} = this.data
    videoUpdateTime.splice(videoUpdateTime.findIndex(item=> item.vid ===vid),1)
    this.setData({
      videoUpdateTime
    })
  },
  //下拉刷新
  handlerRefresh(){
    this.getVideoListData(this.data.navId)
  },
  //上拉加载
  handlerTolower(){
    const {videoList} = this.data
    const newVideoList = [...videoList.slice(0,8)]
    if(newVideoList.length){
      videoList.push(...newVideoList)
    }
    this.setData({
      videoList
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})